package net.gd.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import net.gd.domain.UdfModelInfo;
import net.gd.utils.Constants;
import net.gd.utils.CustomizeSpringContext;

public class UdfModelInfoDaoImpl extends JdbcTemplate implements UdfModelInfoDao {

  private static Logger logger = Logger.getLogger(UdfModelInfoDaoImpl.class);
  
  private DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");

  @Override
  public String create(String modelName) throws Exception {
    String insertSql =
        "insert into udf_model_info(model_id, model_name, create_datetime) " + "values (?,?,?)";
    String modelInfoId = df.format(new Date());
    this.update(insertSql, modelInfoId, modelName, new Date());
    return modelInfoId;
  }


  public static void main(String[] args) throws Exception {
    UdfModelInfoDao dao = (UdfModelInfoDao) CustomizeSpringContext.getBean(UdfModelInfoDao.class);
    // UdfModelInfo info = new UdfModelInfo();
    // info.setModelName("hello3");
    // info.setModelContent("println(\"hello world\")");
    // info.setModelId("20180202000214");
    // info.setLangType("scala");
    // info.setModelStatus("SUCCESS");
    // info.setTopicId("topic1");
    // info.setCreateUser("user_test");

    // String rs = dao.create("hello2");
    // System.out.println(rs);
    // dao.saveOrUpdate(info);

    System.out.println(dao.get("20180202010712684"));
  }

  @Override
  public String saveOrUpdate(UdfModelInfo modelInfo) throws Exception {
    StringBuilder sql = new StringBuilder();
    if (modelInfo.getModelId() != null) {
      // update
      sql.append("update udf_model_info set ");
      if (modelInfo.getLangType() != null) {
        sql.append("lang_type = '").append(modelInfo.getLangType()).append("',");
      }
      if (modelInfo.getModelContent() != null) {
        sql.append("model_content = '").append(modelInfo.getModelContent()).append("',");
      }
      if (modelInfo.getModelName() != null) {
        sql.append("model_name = '").append(modelInfo.getModelName()).append("',");
      }
      if (modelInfo.getTopicId() != null) {
        sql.append("topic_id = '").append(modelInfo.getTopicId()).append("',");
      }
      if (modelInfo.getCreateUser() != null) {
        sql.append("create_user = '").append(modelInfo.getCreateUser()).append("',");
      }
      if (modelInfo.getModelStatus() != null) {
        sql.append("model_status = '").append(modelInfo.getModelStatus()).append("',");
      }
      sql.append("update_datetime='");
      sql.append(new SimpleDateFormat(Constants.DATETIME_FORMAT).format(new Date()));
      sql.append("' ");
      sql.append(" where model_id='").append(modelInfo.getModelId()).append("'");
      logger.info("update sql: " + sql.toString());
      this.execute(sql.toString());
      return modelInfo.getModelId();
    } else {
      // save
      String modelId = df.format(new Date());
      sql.append("insert into udf_model_info");
      sql.append(
          "(model_id,model_name,lang_type,model_content,create_user,create_datetime,update_datetime,topic_id)");
      sql.append("values(?,?,?,?,?,?,?,?)");
      logger.info("insert sql: " + sql.toString());
      this.update(sql.toString(), modelId, modelInfo.getModelName(), modelInfo.getLangType(),
          modelInfo.getModelContent(), modelInfo.getCreateUser(), new Date(),new Date(),
          modelInfo.getTopicId());
      return modelId;
    }

  }


  @Override
  public UdfModelInfo get(String modelId) throws Exception {

    String sql =
        "select model_id,model_name,lang_type,model_content,model_status,create_user,create_datetime,update_datetime,topic_id"
            + " from udf_model_info where model_id = ?";
    UdfModelInfo info = null;
    try {
      info = this.queryForObject(sql, new Object[] {modelId}, infoMapper);
    } catch (Exception e) {
      return null;
    }
    return info;
  }

  private RowMapper<UdfModelInfo> infoMapper = new RowMapper<UdfModelInfo>() {

    @Override
    public UdfModelInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
      UdfModelInfo info = new UdfModelInfo();
      info.setModelId(rs.getString("model_id"));
      info.setModelName(rs.getString("model_name"));
      info.setLangType(rs.getString("lang_type"));
      info.setModelContent(rs.getString("model_content"));
      info.setModelStatus(rs.getString("model_status"));
      info.setCreateUser(rs.getString("create_user"));
      info.setCreateDatetime(rs.getDate("create_datetime"));
      info.setUpdateDatetime(rs.getDate("update_datetime"));
      info.setTopicId(rs.getString("topic_id"));
      return info;
    }
  };

  @Override
  public List<UdfModelInfo> list(String modelId, String modelName) throws Exception {

    String sql =
        "select model_id,model_name,lang_type,model_content,model_status,create_user,create_datetime,update_datetime,topic_id"
            + " from udf_model_info where 1 = 1 ";
    if (StringUtils.isNotBlank(modelId)) {
      sql += " and model_id = '" + modelId + "'";
    } else if (StringUtils.isNotBlank(modelName)) {
      sql += " and model_name like '%" + modelName + "%'";
    }
    List<UdfModelInfo> list = new ArrayList<UdfModelInfo>();
    try {
      list = this.query(sql, infoMapper);
    } catch (Exception e) {
      return null;
    }
    return list;
  }



}
